<script setup lang="ts" name="BpmnPreviewsDialog">
import { useModelerStore } from '@/store/bpmnProcess/modelerStore'
import BpmnModdle from 'bpmn-moddle'
import { errorMessage } from '@/utils/message'

const moddle = new BpmnModdle()

const visible = ref(false)
const title = ref('预览文件')
const type = ref('')
const doc = ref('')

const showDialog = async (v) => {
  type.value = v.toUpperCase()
  try {
    const modeler = useModelerStore().getModeler

    if (!modeler) {
      return errorMessage('模型加载失败，请刷新重试')
    }

    if (type.value === 'XML') {
      const { xml } = await modeler.saveXML({ format: true, preamble: true })
      doc.value = xml
    } else {
      const { xml } = await modeler.saveXML({ format: true })
      const jsonStr = await moddle.fromXML(xml)
      doc.value = JSON.stringify(jsonStr, null, 2)
    }
    visible.value = true
  } catch (e) {
    errorMessage((e as Error).message || (e as string))
  }
}
defineExpose({ showDialog })

const closeDialog = () => {
  visible.value = false
}
</script>

<template>
  <el-dialog class="process-preview-dialog" v-model="visible" append-to-body destroy-on-close :show-close="false">
    <template #header>
      <div class="flow-header">
        <div class="left-wrap">
          <h2>{{ title }}</h2>
          <el-tag class="ml-10px">{{ type }}</el-tag>
        </div>
        <div class="center-wrap"></div>
        <div class="right-wrap">
          <el-button type="info" link @click="closeDialog">
            <svg-icon icon="ep:close"></svg-icon>
          </el-button>
        </div>
      </div>
    </template>
    <div class="codemirror-body">
      <VueCodemirror :lang="type" :doc="doc"></VueCodemirror>
    </div>
  </el-dialog>
</template>

<style scoped lang="scss">
.flow-header {
  display: flex;
  align-items: center;
  height: 54px;

  .left-wrap {
    display: flex;

    h2 {
      padding: 0 0 0 20px;
      font-size: 16px;
      text-align: center;
    }
  }

  .center-wrap {
    flex: 1;
  }

  .left-wrap,
  .right-wrap {
    .el-button {
      width: 54px;
      height: 54px;

      .el-icon {
        font-size: 20px !important;
      }
    }

    .el-button+.el-button {
      margin-left: 0;
    }
  }
}

.codemirror-body {
  position: relative;
  display: flex;
  flex: 1;
  overflow: hidden;
}
</style>
<style lang="scss">
.process-preview-dialog {
  width: 70%;
  height: 70vh;

  >.el-dialog__header {
    position: relative;
    padding: 0;
  }

  >.el-dialog__body {
    position: relative;
    display: flex;
  }
}
</style>
